import os
import time
from pathlib import Path

import logging
import pytest
import yamail

from config.config import Config


class Tools():
    def __init__(self):
        self.cfg = Config()
        self.logger = self.get_logger('Tools')


    @staticmethod
    def resolve_path(relative_path):
        """
        动态解析项目内任意层级的文件路径
        :param relative_path: 相对于项目根目录的路径，如 "Data/accountInfo.yaml"
        :return: 绝对路径字符串
        """
        # 获取项目根目录（假设Tools.py在LongGuoUI/Tools/下）
        base_dir = Path(__file__).parent.parent
        # 拼接并标准化路径
        return str((base_dir / relative_path).resolve())


    #邮件
    def email(self,subject,content,
              attachments=None,
              sender = Config().get_sender(),
              receiver = Config().get_receiver(),
              authorization_code = Config().get_authorization_code(),
              host = Config().get_host(),
              port = Config().get_port()
              ):
        """
        发送邮件
        :param subject: 主题
        :param content: 正文
        :param sender: 发件人
        :param receiver: 收件人
        :param authorization_code: 授权码
        :param host: 协议
        :param port: 端口号
        :return:
        """
        try:
            # #准备附件
            #
            # for file in attachments:
            #     path = Tools.resolve_path(file)
            #     if not Path(path).exists():
            #         self.logger.info('邮件附件不存在')

            #发送邮件
            with yamail.SMTP(user=sender,password=authorization_code,host=host,port=port)as email:
                email.send(to=receiver,subject=subject,contents=content,attachments=attachments)
                return True
        except Exception as e:
            self.logger.error(f'邮件发送失败:{str(e)}')
            return False


    #日志
    def get_logger(self, name='UIAutomation'):
        # 获取当前时间
        now = time.strftime('%Y-%m-%d-%H-%M-%S', time.localtime(time.time()))
        # 创建一个logger
        """获取配置好的logger对象（带防重复创建检查）"""
        logger = logging.getLogger(name)
        if not logger.handlers:  # 避免重复添加handler
            logger.setLevel(logging.DEBUG)  # ← 这里的level控制logger本身

        # 控制台handler
        console_handler = logging.StreamHandler()
        console_handler.setLevel(logging.INFO)  # ← 可单独设置handler级别

        # 文件handler
        file_handler = logging.FileHandler(Tools.resolve_path(f"Log/log{now}.log"), encoding='utf-8')

        file_handler.setLevel(logging.DEBUG)  # ← 文件记录更详细级别

        # 添加格式和handler
        formatter = logging.Formatter('%(lineno)d - %(name)s - %(levelname)s - %(message)s - %(asctime)s')
        console_handler.setFormatter(formatter)
        file_handler.setFormatter(formatter)
        logger.addHandler(console_handler)
        logger.addHandler(file_handler)

        return logger  # ← 返回配置好的logger对象

    # # @staticmethod
    # def generate_allure_report(test_path, report_dir, open_browser=True):
    #     raw_dir = Path(report_dir) / "allure_raw"
    #     pytest.main([test_path, "-v", f"--alluredir={raw_dir}"])
    #     os.system(f'allure generate {raw_dir} -o {report_dir}/allure_html --clean')
    #     if open_browser:
    #         os.system(f'allure open {report_dir}/allure_html')

    @staticmethod  # 添加此装饰器
    def generate_allure_report(test_path, report_dir):
        """静态方法：生成Allure报告"""
        raw_dir = os.path.join(report_dir, "allure_raw")

        # 添加编码参数和环境变量
        os.environ['PYTHONUTF8'] = '1'  # 强制Python使用UTF-8
        pytest.main([
            str(test_path),
            "-v",
            f"--alluredir={raw_dir}",
            "--capture=no",  # 禁用输出捕获，避免编码问题
            "--encoding=utf-8"  # 显式指定编码
        ])

        # 生成报告时强制UTF-8
        os.system(
            f'allure generate {raw_dir} -o {os.path.join(report_dir, "allure_html")} '
            '--clean --encoding utf-8'
        )
    def catch_exception(self, func):
        def wrapper(*args, **kwargs):
            try:
                return func(*args, **kwargs)  # 确保返回值被传递
            except Exception as e:
                print(e)

        return wrapper  # 确保返回 wrapper 函数